package com.blrs.web.controller.system;

import java.io.BufferedReader;

import java.io.IOException;
import java.io.InputStreamReader;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Set;


import com.alibaba.fastjson2.JSON;
import com.blrs.common.constant.RouteIndex;
import com.blrs.common.core.domain.entity.SysDept;
import com.blrs.system.service.ISysDeptService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.blrs.common.constant.Constants;
import com.blrs.common.core.domain.AjaxResult;
import com.blrs.common.core.domain.entity.SysMenu;
import com.blrs.common.core.domain.entity.SysUser;
import com.blrs.common.core.domain.model.LoginBody;
import com.blrs.common.utils.SecurityUtils;
import com.blrs.framework.web.service.SysLoginService;
import com.blrs.framework.web.service.SysPermissionService;
import com.blrs.system.service.ISysMenuService;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ISysDeptService deptService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid(), loginBody.getLoginType());
        ajax.put(Constants.TOKEN, token);
        return ajax;

    }


    public static String fetchNetworkTime(String webUrl) throws Exception {
        URL url = new URL(webUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuilder content = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            content.append(inputLine);
        }
        in.close();
        conn.disconnect();
        return content.toString();
    }
    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        SysDept sysDept = deptService.selectDeptById(SecurityUtils.getOrgId());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("orgId", SecurityUtils.getOrgId());
        ajax.put("orgName", sysDept.getDeptName());
        ajax.put("permissions", permissions);
        ajax.put("companyType", sysDept.getCompanyType());
        ajax.put("isCertified", sysDept.getIsCertified());
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }


    public static String getNetworkTime(String webUrl) {
        try {
            URL url=new URL(webUrl);
            URLConnection conn=url.openConnection();
            conn.connect();
            long dateL=conn.getDate();
            Date date=new Date(dateL); //在这里，如果是想返回sql的Date类型则修改方法的返回类型　　　　　　 //将目前获取到的网络时间util.Date转换成sql.Date的操作如下： 　　　　　 // java.sql.Date date1=new java.sql.Date(date.getTime());//年 月 日 　　　　　 //java.sql.Time date2=new java.sql.Time(date.getTime());//时   分    秒 　　　　　 //java.sql.Timestamp date3=new java.sql.Timestamp(date.getTime());//年  月 日  时  分   秒 毫秒 　　　　　 //System.out.println("输出当前时间年月日"+date1);　　　　　　// System.out.println("输出当前时间时分秒"+date2);　　　　　　//System.out.println("输出当前时间年月日时分秒毫秒"+date3);　　　　　　　//以下是将时间转换成String类型并返回
            SimpleDateFormat dateFormat=new SimpleDateFormat("YYYYMMddHHmm");
            return dateFormat.format(date);
        }catch (MalformedURLException e) {
            e.printStackTrace();
        }catch (IOException e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return "";
    }
}
